package com.cxm.qyyz.core.http.interceptor;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class CacheInterceptor implements Interceptor {

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        String method = request.method();
        Map<String, List<String>> headers = request.headers().toMultimap();
        if (headers.containsKey("shouldKeepCache") && "get".equalsIgnoreCase(method)) {
            Response response = chain.proceed(request);
            int duration = 60 * 60 * 3;
            response = response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, only-if-cached, max-age=" + duration)
                    .build();
            return response;
        }
        return chain.proceed(request);
    }
}
